<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 9/30/14
 * Time: 5:43 PM
 */

namespace loader;

URLClassLoader::init();

/**
 * The IClassLoader is user to implement classes
 * for loading them without includes
 */
class URLClassLoader
{

  private static $localPackages = array('exception','message', 'files', 'imgs', 'loader', 'log', 'parser', 'test');
  private static $webPackages = array('template', 'controller');
  private static $dbPackages = array('orm', 'base', 'sql', 'mysql');

  public static $loader;

  public static function init()
  {
    if (self::$loader == NULL)
      self::$loader = new self();

    return self::$loader;
  }

  public function __construct()
  {
    spl_autoload_register(array($this, 'loadClass'));
  }

  public function loadClass($class)
  {
    $package = "";
    $nameSpace = $this->getNameSpace($class);

    if (in_array($nameSpace, self::$localPackages)) {
      $package = 'local';
    } else if (in_array($nameSpace, self::$webPackages)) {
      $package = 'web';
    } else if (in_array($nameSpace, self::$dbPackages)) {
      $package = 'db';
    }

    $pureClassName = $this->getPureClassName($class);

    $file = $this->listFiles(NYMPH_ROOT . "/" . $package . "/" . $nameSpace . "/", $pureClassName);
    include_once($file);
//    set_include_path('');
//    spl_autoload_extensions('.php');
//    spl_autoload($class);
  }

  public function getNameSpace($class)
  {
    $nameSpaceEndPos = strpos($class, "\\");
    return substr($class, 0, $nameSpaceEndPos);
  }

  public function getPureClassName($classNameWithNamespace)
  {
    $nameSpaceEndPos = strpos($classNameWithNamespace, "\\");
    return substr($classNameWithNamespace, $nameSpaceEndPos + 1);
  }

  public function listFiles($dir, $class)
  {
    $needle = "";
    $files = scandir($dir);
    foreach ($files as $file) {
      if ($file != ".." && $file != ".") {
        if (is_dir($dir . $file)) {
          $needle = $this->listFiles($dir . $file . "/", $class);
          if ($needle != null) {
            return $needle;
          }
        } else {
          if (strpos($file, $class) === 0) {
            return $dir . $file;
          }
//          array_push($classesToLoad, $dir . $file);
        }
      }
    }
    return null;
  }

}